<!DOCTYPE html>
<html lang=zh>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  
  
  <title>js中的跨域及其解决的办法 | 永恒的金色年华</title>
  <meta name="description" content="js中的跨域及其解决的办法一、什么是跨域？在了解跨域之前，首先要知道什么是同源策略（same-origin policy）。简单来讲同源策略就是浏览器为了保证用户信息的安全，防止恶意的网站窃取数据，禁止不同域之间的JS进行交互。对于浏览器而言只要域名、协议、端口其中一个不同就会引发同源策略，从而限制他们之间如下的交互行为： 1.Cookie、LocalStorage和IndexDB无法读取； 2.">
<meta property="og:type" content="article">
<meta property="og:title" content="js中的跨域及其解决的办法">
<meta property="og:url" content="https://xulujin.gitee.io/blog/2018/12/05/js%E4%B8%AD%E7%9A%84%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3/index.html">
<meta property="og:site_name" content="LuKing">
<meta property="og:description" content="js中的跨域及其解决的办法一、什么是跨域？在了解跨域之前，首先要知道什么是同源策略（same-origin policy）。简单来讲同源策略就是浏览器为了保证用户信息的安全，防止恶意的网站窃取数据，禁止不同域之间的JS进行交互。对于浏览器而言只要域名、协议、端口其中一个不同就会引发同源策略，从而限制他们之间如下的交互行为： 1.Cookie、LocalStorage和IndexDB无法读取； 2.">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://images2017.cnblogs.com/blog/1191190/201708/1191190-20170824154926855-473423436.png">
<meta property="article:published_time" content="2018-12-05T10:40:25.000Z">
<meta property="article:modified_time" content="2020-06-21T13:10:21.274Z">
<meta property="article:author" content="LuKing-Xun">
<meta property="article:tag" content="javascript">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://images2017.cnblogs.com/blog/1191190/201708/1191190-20170824154926855-473423436.png">
  <!-- Canonical links -->
  <link rel="canonical" href="https://xulujin.gitee.io/blog/2018/12/05/js%E4%B8%AD%E7%9A%84%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3/index.html">
  
    <link rel="alternate" href="/atom.xml" title="LuKing" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/blog/css/style.css">

  
  
    <link rel="stylesheet" href="//cdn.jsdelivr.net/npm/gitment@0.0.3/style/default.min.css">
  
  
  
<meta name="generator" content="Hexo 5.2.0"></head>


<body class="main-center theme-black" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="https://github.com/1314xulujin" target="_blank">
          <img class="img-circle img-rotate" src="/blog/images/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">LuKing-Xun</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">前端工程师</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> Shenzhen, China</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="Type something..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav menu-highlight">
        
        
        <li class="menu-item menu-item-home">
          <a href="/blog/.">
            
            <i class="icon icon-home-fill"></i>
            
            <span class="menu-title">Home</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives">
            
            <i class="icon icon-archives-fill"></i>
            
            <span class="menu-title">Archives</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories">
            
            <i class="icon icon-folder"></i>
            
            <span class="menu-title">Categories</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags">
            
            <i class="icon icon-tags"></i>
            
            <span class="menu-title">Tags</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-repository">
          <a href="/blog/repository">
            
            <i class="icon icon-project"></i>
            
            <span class="menu-title">Repository</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-books">
          <a href="/blog/books">
            
            <i class="icon icon-book-fill"></i>
            
            <span class="menu-title">Books</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-links">
          <a href="/blog/links">
            
            <i class="icon icon-friendship"></i>
            
            <span class="menu-title">Links</span>
          </a>
        </li>
        
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about">
            
            <i class="icon icon-cup-fill"></i>
            
            <span class="menu-title">About</span>
          </a>
        </li>
        
      </ul>
      
	
    <ul class="social-links">
    	
        <li><a href="https://github.com/1314xulujin" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="https://mail.qq.com/cgi-bin/loginpage" target="_blank" title="Email" data-toggle=tooltip data-placement=top><i class="icon icon-email"></i></a></li>
        
        <li><a href="/blog/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>一如前端深似海,回头?...没头回了!</p>
            </div>
        </div>
    </div>
</div>

    
      

    
      
  <div class="widget">
    <h3 class="widget-title">Tags</h3>
    <div class="widget-body">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/BFC/" rel="tag">BFC</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/BootStrap/" rel="tag">BootStrap</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/ES6/" rel="tag">ES6</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/HTML5-css3/" rel="tag">HTML5+css3</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/OOP%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E6%80%9D%E6%83%B3/" rel="tag">OOP面向对象思想</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/Storage%E5%AD%98%E5%82%A8/" rel="tag">Storage存储</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/Web-Worker/" rel="tag">Web Worker</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/ajax/" rel="tag">ajax</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/call%E5%92%8Capply/" rel="tag">call和apply</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/css3/" rel="tag">css3</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/git/" rel="tag">git</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/hexo%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2/" rel="tag">hexo搭建博客</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/html4/" rel="tag">html4</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/jQuery/" rel="tag">jQuery</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/java/" rel="tag">java</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/javascript/" rel="tag">javascript</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/js/" rel="tag">js</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/photoshop/" rel="tag">photoshop</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/vue/" rel="tag">vue</a><span class="tag-list-count">8</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/webpack/" rel="tag">webpack</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/websocket/" rel="tag">websocket</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/window10/" rel="tag">window10</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E5%85%B6%E4%BB%96/" rel="tag">其他</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E5%86%B7%E7%9F%A5%E8%AF%86/" rel="tag">冷知识</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E5%87%BD%E6%95%B0%E6%9F%AF%E9%87%8C%E5%8C%96/" rel="tag">函数柯里化</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E5%89%8D%E7%AB%AF/" rel="tag">前端</a><span class="tag-list-count">5</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/" rel="tag">前端工程化</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E5%89%8D%E7%AB%AF%E9%9D%A2%E8%AF%95%E9%A2%98/" rel="tag">前端面试题</a><span class="tag-list-count">9</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8FUI%E6%A1%86%E6%9E%B6/" rel="tag">微信小程序UI框架</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E6%95%99%E7%A8%8B/" rel="tag">教程</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E6%99%BA%E6%89%AC%E4%BF%A1%E8%BE%BE/" rel="tag">智扬信达</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E6%9C%AC%E7%A7%91%E8%80%83%E8%AF%95%E7%A7%91%E7%9B%AE/" rel="tag">本科考试科目</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E8%B7%A8%E5%9F%9F/" rel="tag">跨域</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E8%BD%AF%E4%BB%B6%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="tag">软件设计模式</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E8%BD%AF%E5%AE%9E%E5%8A%9B/" rel="tag">软实力</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E9%9D%A2%E8%AF%95/" rel="tag">面试</a><span class="tag-list-count">10</span></li><li class="tag-list-item"><a class="tag-list-link" href="/blog/tags/%E9%9D%A2%E8%AF%95%E9%A2%98/" rel="tag">面试题</a><span class="tag-list-count">7</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget-body tagcloud">
      <a href="/blog/tags/BFC/" style="font-size: 13px;">BFC</a> <a href="/blog/tags/BootStrap/" style="font-size: 13px;">BootStrap</a> <a href="/blog/tags/ES6/" style="font-size: 13px;">ES6</a> <a href="/blog/tags/HTML5-css3/" style="font-size: 13px;">HTML5+css3</a> <a href="/blog/tags/OOP%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E6%80%9D%E6%83%B3/" style="font-size: 13px;">OOP面向对象思想</a> <a href="/blog/tags/Storage%E5%AD%98%E5%82%A8/" style="font-size: 13px;">Storage存储</a> <a href="/blog/tags/Web-Worker/" style="font-size: 13px;">Web Worker</a> <a href="/blog/tags/ajax/" style="font-size: 13px;">ajax</a> <a href="/blog/tags/call%E5%92%8Capply/" style="font-size: 13px;">call和apply</a> <a href="/blog/tags/css3/" style="font-size: 13px;">css3</a> <a href="/blog/tags/git/" style="font-size: 13px;">git</a> <a href="/blog/tags/hexo%E6%90%AD%E5%BB%BA%E5%8D%9A%E5%AE%A2/" style="font-size: 13px;">hexo搭建博客</a> <a href="/blog/tags/html4/" style="font-size: 13px;">html4</a> <a href="/blog/tags/jQuery/" style="font-size: 13px;">jQuery</a> <a href="/blog/tags/java/" style="font-size: 13px;">java</a> <a href="/blog/tags/javascript/" style="font-size: 13.14px;">javascript</a> <a href="/blog/tags/js/" style="font-size: 13px;">js</a> <a href="/blog/tags/photoshop/" style="font-size: 13px;">photoshop</a> <a href="/blog/tags/vue/" style="font-size: 13.71px;">vue</a> <a href="/blog/tags/webpack/" style="font-size: 13.14px;">webpack</a> <a href="/blog/tags/websocket/" style="font-size: 13px;">websocket</a> <a href="/blog/tags/window10/" style="font-size: 13px;">window10</a> <a href="/blog/tags/%E5%85%B6%E4%BB%96/" style="font-size: 13px;">其他</a> <a href="/blog/tags/%E5%86%B7%E7%9F%A5%E8%AF%86/" style="font-size: 13.14px;">冷知识</a> <a href="/blog/tags/%E5%87%BD%E6%95%B0%E6%9F%AF%E9%87%8C%E5%8C%96/" style="font-size: 13px;">函数柯里化</a> <a href="/blog/tags/%E5%89%8D%E7%AB%AF/" style="font-size: 13.43px;">前端</a> <a href="/blog/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/" style="font-size: 13px;">前端工程化</a> <a href="/blog/tags/%E5%89%8D%E7%AB%AF%E9%9D%A2%E8%AF%95%E9%A2%98/" style="font-size: 13.86px;">前端面试题</a> <a href="/blog/tags/%E5%BE%AE%E4%BF%A1%E5%B0%8F%E7%A8%8B%E5%BA%8FUI%E6%A1%86%E6%9E%B6/" style="font-size: 13px;">微信小程序UI框架</a> <a href="/blog/tags/%E6%95%99%E7%A8%8B/" style="font-size: 13px;">教程</a> <a href="/blog/tags/%E6%99%BA%E6%89%AC%E4%BF%A1%E8%BE%BE/" style="font-size: 13.29px;">智扬信达</a> <a href="/blog/tags/%E6%9C%AC%E7%A7%91%E8%80%83%E8%AF%95%E7%A7%91%E7%9B%AE/" style="font-size: 13px;">本科考试科目</a> <a href="/blog/tags/%E8%B7%A8%E5%9F%9F/" style="font-size: 13px;">跨域</a> <a href="/blog/tags/%E8%BD%AF%E4%BB%B6%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" style="font-size: 13px;">软件设计模式</a> <a href="/blog/tags/%E8%BD%AF%E5%AE%9E%E5%8A%9B/" style="font-size: 13px;">软实力</a> <a href="/blog/tags/%E9%9D%A2%E8%AF%95/" style="font-size: 14px;">面试</a> <a href="/blog/tags/%E9%9D%A2%E8%AF%95%E9%A2%98/" style="font-size: 13.57px;">面试题</a>
    </div>
  </div>

    
      
  <div class="widget">
    <h3 class="widget-title">Archive</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2022/06/">六月 2022</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2022/05/">五月 2022</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2022/01/">一月 2022</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/11/">十一月 2021</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/08/">八月 2021</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/06/">六月 2021</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/05/">五月 2021</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/04/">四月 2021</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2021/02/">二月 2021</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2020/09/">九月 2020</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2020/08/">八月 2020</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2020/07/">七月 2020</a><span class="archive-list-count">7</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2020/06/">六月 2020</a><span class="archive-list-count">12</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2020/05/">五月 2020</a><span class="archive-list-count">10</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2020/04/">四月 2020</a><span class="archive-list-count">8</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2020/03/">三月 2020</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2020/02/">二月 2020</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2020/01/">一月 2020</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2019/12/">十二月 2019</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2019/11/">十一月 2019</a><span class="archive-list-count">7</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2019/10/">十月 2019</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2018/12/">十二月 2018</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/blog/archives/2018/10/">十月 2018</a><span class="archive-list-count">6</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled no-thumbnail">
        
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/blog/2022/06/16/%E5%B0%86node-sass%E6%8D%A2%E6%88%90dart-sass/" class="title">将node-sass换成dart-sass</a>
              </p>
              <p class="item-date">
                <time datetime="2022-06-16T04:55:29.000Z" itemprop="datePublished">2022-06-16</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/blog/2022/05/25/%E8%87%AA%E5%B7%B1%E5%AF%B9%E8%BD%AF%E4%BB%B6%E5%BC%80%E5%8F%91%E5%8F%8A%E4%BA%A4%E4%BB%98%E6%B5%81%E7%A8%8B%E7%90%86%E8%A7%A3/" class="title">自己对软件开发及交付流程理解</a>
              </p>
              <p class="item-date">
                <time datetime="2022-05-25T06:31:29.000Z" itemprop="datePublished">2022-05-25</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/blog/2022/05/16/web%E5%89%8D%E7%AB%AF%E5%B8%B8%E8%A7%81%E5%85%B3%E9%94%AE%E8%AF%8D/" class="title">web前端关键词</a>
              </p>
              <p class="item-date">
                <time datetime="2022-05-16T03:21:19.000Z" itemprop="datePublished">2022-05-16</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/blog/2022/01/19/%E5%AD%97%E8%8A%82%E9%A3%9E%E4%B9%A6%E9%9D%A2%E8%AF%95%E9%A2%98_20220119/" class="title">腾讯互娱面试题</a>
              </p>
              <p class="item-date">
                <time datetime="2022-01-19T02:10:23.000Z" itemprop="datePublished">2022-01-19</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                
              </p>
              <p class="item-title">
                <a href="/blog/2021/11/12/js%E5%B0%86%E5%A4%9A%E4%B8%AA%E5%9B%BE%E7%89%87%E6%8B%BC%E5%9C%A8%E4%B8%80%E8%B5%B7%E4%B8%8B%E8%BD%BD%E6%88%90%E4%B8%80%E5%BC%A0%E5%9B%BE%E7%89%87/" class="title">(no title)</a>
              </p>
              <p class="item-date">
                <time datetime="2021-11-12T04:28:18.079Z" itemprop="datePublished">2021-11-12</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<main class="main" role="main">
  <div class="content">
  <article id="post-js中的跨域问题解决" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      js中的跨域及其解决的办法
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/blog/2018/12/05/js%E4%B8%AD%E7%9A%84%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3/" class="article-date">
	  <time datetime="2018-12-05T10:40:25.000Z" itemprop="datePublished">2018-12-05</time>
	</a>
</span>
        
        
  <span class="article-tag">
    <i class="icon icon-tags"></i>
	<a class="article-tag-link-link" href="/blog/tags/javascript/" rel="tag">javascript</a>
  </span>


        

        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/blog/2018/12/05/js%E4%B8%AD%E7%9A%84%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3/#comments" class="article-comment-link">Comments</a></span>
        
      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <h1 id="js中的跨域及其解决的办法"><a href="#js中的跨域及其解决的办法" class="headerlink" title="js中的跨域及其解决的办法"></a>js中的跨域及其解决的办法</h1><h3 id="一、什么是跨域？"><a href="#一、什么是跨域？" class="headerlink" title="一、什么是跨域？"></a>一、什么是跨域？</h3><p>在了解跨域之前，首先要知道什么是同源策略（same-origin policy）。简单来讲同源策略就是浏览器为了保证用户信息的安全，防止恶意的网站窃取数据，禁止不同域之间的JS进行交互。对于浏览器而言只要域名、协议、端口其中一个不同就会引发同源策略，从而限制他们之间如下的交互行为：</p>
<p>1.Cookie、LocalStorage和IndexDB无法读取；</p>
<p>2.DOM无法获得；</p>
<p>3.AJAX请求不能发送。</p>
<p>跨域的严格一点的定义是：只要协议，域名，端口有任何一个的不同，就被当作是跨域。</p>
<p>如下表所示：    </p>
<table>
<thead>
<tr>
<th>URL</th>
<th>说明</th>
<th>是否允许通信</th>
</tr>
</thead>
<tbody><tr>
<td><a target="_blank" rel="noopener" href="http://www.a.com/a.js">http://www.a.com/a.js</a><br><a target="_blank" rel="noopener" href="http://www.a.com/b.js">http://www.a.com/b.js</a></td>
<td>同一域名下</td>
<td>允许</td>
</tr>
<tr>
<td><a target="_blank" rel="noopener" href="http://www.a.com/lab/a.js">http://www.a.com/lab/a.js</a><br><a target="_blank" rel="noopener" href="http://www.a.com/script/b.js">http://www.a.com/script/b.js</a></td>
<td>同一域名下不同文件夹</td>
<td>允许</td>
</tr>
<tr>
<td><a target="_blank" rel="noopener" href="http://www.a.com:8000/a.js">http://www.a.com:8000/a.js</a><br><a target="_blank" rel="noopener" href="http://www.a.com/b.js">http://www.a.com/b.js</a></td>
<td>同一域名，不同端口</td>
<td>不允许</td>
</tr>
<tr>
<td><a target="_blank" rel="noopener" href="http://www.a.com/a.js">http://www.a.com/a.js</a><br><a target="_blank" rel="noopener" href="https://www.a.com/b.js">https://www.a.com/b.js</a></td>
<td>同一域名，不同协议</td>
<td>不允许</td>
</tr>
<tr>
<td><a target="_blank" rel="noopener" href="http://www.a.com/a.js">http://www.a.com/a.js</a><br><a target="_blank" rel="noopener" href="http://70.32.92.74/b.js">http://70.32.92.74/b.js</a></td>
<td>域名和域名对应ip</td>
<td>不允许</td>
</tr>
<tr>
<td><a target="_blank" rel="noopener" href="http://www.a.com/a.js">http://www.a.com/a.js</a><br><a target="_blank" rel="noopener" href="http://script.a.com/b.js">http://script.a.com/b.js</a></td>
<td>主域相同，子域不同</td>
<td>不允许</td>
</tr>
<tr>
<td><a target="_blank" rel="noopener" href="http://www.a.com/a.js">http://www.a.com/a.js</a><br><a target="_blank" rel="noopener" href="http://a.com/b.js">http://a.com/b.js</a></td>
<td>同一域名，不同二级域名（同上）</td>
<td>不允许（cookie这种情况下也不允许访问）</td>
</tr>
<tr>
<td><a target="_blank" rel="noopener" href="http://www.cnblogs.com/a.js">http://www.cnblogs.com/a.js</a><br><a target="_blank" rel="noopener" href="http://www.a.com/b.js">http://www.a.com/b.js</a></td>
<td>不同域名</td>
<td>不允许</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</tbody></table>
<p>特别注意两点：</p>
<p>第一，如果是协议和端口造成的跨域问题“前台”是无能为力的，</p>
<p>第二：在跨域问题上，域仅仅是通过“URL的首部”来识别而不会去尝试判断相同的ip地址对应着两个域或两个域是否在同一个ip上。</p>
<p>“URL的首部”指window.location.protocol +window.location.host，也可以理解为“Domains, protocols and ports must match”。</p>
<h3 id="二、为什么浏览器要限制跨域访问呢？"><a href="#二、为什么浏览器要限制跨域访问呢？" class="headerlink" title="二、为什么浏览器要限制跨域访问呢？"></a>二、为什么浏览器要限制跨域访问呢？</h3><p>原因就是安全问题：如果一个网页可以随意地访问另外一个网站的资源，那么就有可能在客户完全不知情的情况下出现安全问题。比如下面的操作就有安全问题：</p>
<p>1.用户访问<a target="_blank" rel="noopener" href="http://www.mybank.com,登陆并进行网银操作,这时cookie啥的都生成并存放在浏览器;/">www.mybank.com，登陆并进行网银操作，这时cookie啥的都生成并存放在浏览器；</a></p>
<p>2.用户突然想起件事，并迷迷糊糊的访问了一个邪恶的网站<a target="_blank" rel="noopener" href="http://www.xiee.com;/">www.xiee.com；</a></p>
<p>3.这时该网站就可以在它的页面中，拿到银行的cookie，比如用户名，登陆token等，然后发起对<a target="_blank" rel="noopener" href="http://www.mybank.com的操作;/">www.mybank.com的操作；</a></p>
<p>4.如果这时浏览器不予限制，并且银行也没有做响应的安全处理的话，那么用户的信息有可能就这么泄露了。</p>
<h3 id="三、为什么要跨域？"><a href="#三、为什么要跨域？" class="headerlink" title="三、为什么要跨域？"></a>三、为什么要跨域？</h3><p>既然有安全问题，那为什么又要跨域呢？ 有时公司内部有多个不同的子域，比如一个是location.company.com ,而应用是放在app.company.com , 这时想从 app.company.com去访问 location.company.com 的资源就属于跨域。</p>
<h3 id="四、解决跨域问题的方法："><a href="#四、解决跨域问题的方法：" class="headerlink" title="四、解决跨域问题的方法："></a>四、解决跨域问题的方法：</h3><h4 id="1-跨域资源共享（CORS）"><a href="#1-跨域资源共享（CORS）" class="headerlink" title="1.跨域资源共享（CORS）"></a>1.跨域资源共享（CORS）</h4><p>CORS（Cross-Origin Resource Sharing）跨域资源共享，定义了必须在访问跨域资源时，浏览器与服务器应该如何沟通。CORS背后的基本思想就是使用自定义的HTTP头部让浏览器与服务器进行沟通，从而决定请求或响应是应该成功还是失败。</p>
<p>服务器端对于CORS的支持，主要就是通过设置Access-Control-Allow-Origin来进行的。如果浏览器检测到相应的设置，就可以允许Ajax进行跨域的访问。</p>
<p>只需要在后台中加上响应头来允许域请求！在被请求的Response header中加入以下设置，就可以实现跨域访问了！</p>
<p>如下所示：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//指定允许其他域名访问</span></span><br><span class="line"><span class="string">&#x27;Access-Control-Allow-Origin:*&#x27;</span><span class="comment">//或指定域</span></span><br><span class="line"><span class="comment">//响应类型</span></span><br><span class="line"><span class="string">&#x27;Access-Control-Allow-Methods:GET,POST&#x27;</span></span><br><span class="line"><span class="comment">//响应头设置</span></span><br><span class="line"><span class="string">&#x27;Access-Control-Allow-Headers:x-requested-with,content-type&#x27;</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>





<h4 id="2-通过jsonp跨域"><a href="#2-通过jsonp跨域" class="headerlink" title="2.通过jsonp跨域"></a>2.通过jsonp跨域</h4><p>JSONP是JSON with Padding（填充式json）的简写，是应用JSON的一种新方法，只不过是被包含在函数调用中的JSON，例如：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">callback(&#123;<span class="string">&quot;name&quot;</span>,<span class="string">&quot;trigkit4&quot;</span>&#125;);</span><br></pre></td></tr></table></figure>



<p>JSONP由两部分组成：回调函数和数据。回调函数是当响应到来时应该在页面中调用的函数，而数据就是传入回调函数中的JSON数据。</p>
<p><strong>JSONP的原理</strong>：通过script标签引入一个js文件，这个js文件载入成功后会执行我们在url参数中指定的函数，并且会把我们需要的json数据作为参数传入。所以jsonp是需要服务器端的页面进行相应的配合的。（即用JavaScript动态加载一个script文件，同时定义一个callback函数给script执行而已。）</p>
<p>在js中，我们直接用XMLHttpRequest请求不同域上的数据时，是不可以的。但是，在页面上引入不同域上的js脚本文件却是可以的，jsonp正是利用这个特性来实现的。 例如：有个a.html页面，它里面的代码需要利用ajax获取一个不同域上的json数据，假设这个json数据地址是<a target="_blank" rel="noopener" href="http://example.com/data.php%EF%BC%8C%E9%82%A3%E4%B9%88a.html%E4%B8%AD%E7%9A%84%E4%BB%A3%E7%A0%81%E5%B0%B1%E5%8F%AF%E4%BB%A5%E8%BF%99%E6%A0%B7%EF%BC%9A">http://example.com/data.php，那么a.html中的代码就可以这样：</a></p>
<script type="text/javascript">
    function dosomething(jsondata){
        //处理获得的json数据
    }
</script>
<script src="http://example.com/data.php?callback=dosomething"></script>
<p>js文件载入成功后会<strong>执行</strong>我们在url参数中<strong>指定的函数</strong>，并且会把我们需要的json数据作为参数传入。所以jsonp是需要服务器端的页面进行相应的配合的。</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line">callback = _GET[<span class="string">&#x27;callback&#x27;</span>];<span class="comment">//得到回调函数名</span></span><br><span class="line">data = <span class="keyword">array</span>(<span class="string">&#x27;a&#x27;</span>,<span class="string">&#x27;b&#x27;</span>,<span class="string">&#x27;c&#x27;</span>);<span class="comment">//要返回的数据</span></span><br><span class="line"><span class="keyword">echo</span> callback.<span class="string">&#x27;(&#x27;</span>.json_encode(<span class="variable">$data</span>).<span class="string">&#x27;)&#x27;</span>;<span class="comment">//输出</span></span><br><span class="line"><span class="meta">?&gt;</span></span><br></pre></td></tr></table></figure>



<p>最终，输出结果为：dosomething([‘a’,’b’,’c’]);</p>
<p><img src="https://images2017.cnblogs.com/blog/1191190/201708/1191190-20170824154926855-473423436.png"></p>
<p>如果你的页面使用jquery，那么通过它封装的方法就能很方便的来进行jsonp操作了。jquery会自动生成一个全局函数来替换callback=?中的问号，之后获取到数据后又会自动销毁，实际上就是起一个临时代理函数的作用。$.getJSON方法会自动判断是否跨域，不跨域的话，就调用普通的ajax方法；跨域的话，则会以异步加载js文件的形式来调用jsonp的回调函数。</p>
<script type="text/javascript">
    $.getJSON('http://example.com/data.php?callback=?,function(jsondata)'){
        //处理获得的json数据
    });
</script>
<h5 id="JSONP的优缺点："><a href="#JSONP的优缺点：" class="headerlink" title="JSONP的优缺点："></a>JSONP的优缺点：</h5><p>JSONP的优点是：它不像XMLHttpRequest对象实现的Ajax请求那样受到同源策略的限制；它的兼容性更好，在更加古老的浏览器中都可以运行，不需要XMLHttpRequest或ActiveX的支持；并且在请求完毕后可以通过调用callback的方式回传结果。</p>
<p>JSONP的缺点则是：它只支持GET请求而不支持POST等其它类型的HTTP请求；它只支持跨域HTTP请求这种情况，不能解决不同域的两个页面之间如何进行JavaScript调用的问题。</p>
<h5 id="CORS和JSONP对比："><a href="#CORS和JSONP对比：" class="headerlink" title="CORS和JSONP对比："></a>CORS和JSONP对比：</h5><p>CORS与JSONP相比，无疑更为先进、方便和可靠。</p>
<p>（1）JSONP只能实现GET请求，而CORS支持所有类型的HTTP请求；</p>
<p>（2）使用CORS，开发者可以使用普通的XMLHttpRequest发起请求和获得说句，比起JSONP有更好的错误处理；</p>
<p>（3）JSONP主要被老的浏览器支持，它们往往不支持CORS，而绝大多数现代浏览器都已经支持了CORS；</p>
<h4 id="3-通过修改document-domain来跨子域"><a href="#3-通过修改document-domain来跨子域" class="headerlink" title="3.通过修改document.domain来跨子域"></a>3.通过修改document.domain来跨子域</h4><p>上面的jsonp是来解决ajax跨域请求的，那么如果是需要处理 Cookie 和 iframe 该怎么办呢？这时候就可以通过修改document.domain来跨子域。两个网页一级域名相同，只是二级域名不同，浏览器允许通过设置document.domain共享 Cookie或者处理iframe。比如A网页是<a target="_blank" rel="noopener" href="http://w1.example.com/a.html%EF%BC%8CB%E7%BD%91%E9%A1%B5%E6%98%AFhttp://w2.example.com/b.html%EF%BC%8C%E9%82%A3%E4%B9%88%E5%8F%AA%E8%A6%81%E8%AE%BE%E7%BD%AE%E7%9B%B8%E5%90%8C%E7%9A%84document.domain%EF%BC%8C%E4%B8%A4%E4%B8%AA%E7%BD%91%E9%A1%B5%E5%B0%B1%E5%8F%AF%E4%BB%A5%E5%85%B1%E4%BA%ABCookie%E3%80%82">http://w1.example.com/a.html，B网页是http://w2.example.com/b.html，那么只要设置相同的document.domain，两个网页就可以共享Cookie。</a></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">document</span>.domain = <span class="string">&#x27;example.com&#x27;</span>;</span><br><span class="line"><span class="comment">//现在，A网页通过脚本设置一个 Cookie。</span></span><br><span class="line"><span class="built_in">document</span>.cookie = <span class="string">&quot;test1=hello&quot;</span>;</span><br><span class="line"><span class="comment">//B网页就可以读到这个 Cookie。</span></span><br><span class="line"><span class="keyword">var</span> allCookie = <span class="built_in">document</span>.cookie;</span><br></pre></td></tr></table></figure>



<p>注意，这种方法只适用于 Cookie 和 iframe 窗口，LocalStorage 和 IndexDB 无法通过这种方法，规避同源政策，而要使用下文介绍的PostMessage API。<br>另外，服务器也可以在设置Cookie的时候，指定Cookie的所属域名为一级域名，比如.example.com。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Set</span>-Cookie: key=value; domain=.example.com; path=/</span><br><span class="line"><span class="comment">//这样的话，二级域名和三级域名不用做任何设置，都可以读取这个Cookie。</span></span><br><span class="line"></span><br></pre></td></tr></table></figure>





<p>不同的iframe 之间（父子或同辈），是能够获取到彼此的window对象的，但是你却不能使用获取到的window对象的属性和方法(html5中的postMessage方法是一个例外，还有些浏览器比如ie6也可以使用top、parent等少数几个属性)，总之，你可以当做是只能获取到一个几乎无用的window对象。<br>首先说明一下同域之间的iframe是可以操作的。比如<a target="_blank" rel="noopener" href="http://127.0.0.1/JSONP/a.html%E9%87%8C%E9%9D%A2%E5%B5%8C%E5%85%A5%E4%B8%80%E4%B8%AAiframe%E6%8C%87%E5%90%91http://127.0.0.1/myPHP/b.html%E3%80%82%E9%82%A3%E4%B9%88%E5%9C%A8a.html%E9%87%8C%E9%9D%A2%E6%98%AF%E5%8F%AF%E4%BB%A5%E6%93%8D%E4%BD%9Ciframe%E9%87%8C%E9%9D%A2%E7%9A%84DOM%E7%9A%84%E3%80%82">http://127.0.0.1/JSONP/a.html里面嵌入一个iframe指向http://127.0.0.1/myPHP/b.html。那么在a.html里面是可以操作iframe里面的DOM的。</a></p>
<iframe src="http://127.0.0.1/myPHP/b.html" frameborder="1"></iframe>
<body>
<script type="text/javascript">
var iframe = document.querySelector("iframe");
iframe.onload = function(){
    var win = iframe.contentWindow;
    var doc = win.document;
    var ele = doc.querySelector(".text1");
    var text = ele.innerHTML="123456";
}
</script>
如果两个网页不同源，就无法拿到对方的DOM。典型的例子是iframe窗口和window.open方法打开的窗口，它们与父窗口无法通信。如果两个窗口一级域名相同，只是二级域名不同，那么document.domain属性，就可以规避同源政策，拿到DOM。 

<h4 id="4-使用window-name来进行跨域"><a href="#4-使用window-name来进行跨域" class="headerlink" title="4.使用window.name来进行跨域"></a>4.使用window.name来进行跨域</h4><p>window对象有个name属性，该属性有个特征：即在一个窗口(window)的生命周期内,窗口载入的所有的页面都是共享一个window.name的，每个页面对window.name都有读写的权限，window.name是持久存在一个窗口载入过的所有页面中的，并不会因新页面的载入而进行重置。这个属性的最大特点是，无论是否同源，只要在同一个窗口里，前一个网页设置了这个属性，后一个网页可以读取它。<br>比如：有一个页面a.html,它里面有这样的代码：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.name = <span class="string">&quot;我是a页面设置的&quot;</span>;</span><br><span class="line"><span class="built_in">setTimeout</span>(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">window</span>.location = <span class="string">&quot;http://127.0.0.1/JSONP/b.html&quot;</span>;</span><br><span class="line">&#125;,<span class="number">1000</span>)</span><br></pre></td></tr></table></figure>





<h6 id="b-html页面的代码："><a href="#b-html页面的代码：" class="headerlink" title="b.html页面的代码："></a>b.html页面的代码：</h6><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="built_in">window</span>.name);</span><br></pre></td></tr></table></figure>



<p>​    </p>
<h6 id="a-html页面载入后1秒，跳转到了b-html页面，结果b页面打印出了："><a href="#a-html页面载入后1秒，跳转到了b-html页面，结果b页面打印出了：" class="headerlink" title="a.html页面载入后1秒，跳转到了b.html页面，结果b页面打印出了："></a>a.html页面载入后1秒，跳转到了b.html页面，结果b页面打印出了：</h6><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">我是a页面设置的</span><br></pre></td></tr></table></figure>





<p>可以看到在b.html页面上成功获取到了它的上一个页面a.html给window.name设置的值。如果在之后所有载入的页面都没对window.name进行修改的话，那么所有这些页面获取到的window.name的值都是a.html页面设置的那个值。当然，如果有需要，其中的任何一个页面都可以对window.name的值进行修改。注意，window.name的值只能是字符串的形式，这个字符串的大小最大能允许2M左右甚至更大的一个容量，具体取决于不同的浏览器，但一般是够用了。<br>利用window.name可以对同域或者不同域的之间的js进行交互。<br>那么在a.html页面中，我们怎么把b.html页面载入进来呢？显然我们不能直接在a.html页面中通过改变window.location来载入b.html页面，因为我们想要即使a.html页面不跳转也能得到b.html里的数据。答案就是在a.html页面中使用一个隐藏的iframe来充当一个中间人角色，由iframe去获取b.html的数据，然后a.html再去得到iframe获取到的数据。</p>
<h4 id="5-使用HTML5的window-postMessage方法跨域"><a href="#5-使用HTML5的window-postMessage方法跨域" class="headerlink" title="5.使用HTML5的window.postMessage方法跨域"></a>5.使用HTML5的window.postMessage方法跨域</h4><p>上面两种方法都属于破解，HTML5为了解决这个问题，引入了一个全新的API：跨文档通信 API（Cross-document messaging）。<br>这个API为window对象新增了一个window.postMessage方法，允许跨窗口通信，不论这两个窗口是否同源。目前IE8+、FireFox、Chrome、Opera等浏览器都已经支持window.postMessage方法。<br>举例来说，父窗口<a target="_blank" rel="noopener" href="http://a.com向子窗口http//b.com%E5%8F%91%E6%B6%88%E6%81%AF%EF%BC%8C%E8%B0%83%E7%94%A8postMessage%E6%96%B9%E6%B3%95%E5%B0%B1%E5%8F%AF%E4%BB%A5%E4%BA%86%E3%80%82">http://a.com向子窗口http://b.com发消息，调用postMessage方法就可以了。</a><br>a页面：</p>
<iframe id="frame1" src="http://127.0.0.1/JSONP/b.html" frameborder="1"></iframe>document.getElementById('frame1').onload = function(){
    var win = document.getElementById('frame1').contentWindow;
    win.postMessage("我是来自a页面的","http://127.0.0.1/JSONP/b.html")
}


<p>b页面通过监听message事件可以接受到来自a页面的消息。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.onmessage = <span class="function"><span class="keyword">function</span>(<span class="params">e</span>)</span>&#123;</span><br><span class="line">    e = e || event;</span><br><span class="line">    <span class="built_in">console</span>.log(e.data);<span class="comment">//我是来自a页面的</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<p>子窗口向父窗口发送消息的写法类似。</p>
<p>window.opener.postMessage(‘我是来自b页面的’, ‘<a target="_blank" rel="noopener" href="http://a.com&/#39;">http://a.com&#39;</a>);<br>//父窗口和子窗口都可以通过message事件，监听对方的消息。<br>通过window.postMessage，读写其他窗口的 LocalStorage 也成为了可能。<br>下面是一个例子，主窗口写入iframe子窗口的localStorage。<br>父窗口发送消息代码：</p>
<p>var win = document.getElementsByTagName(‘iframe’)[0].contentWindow;<br>var obj = { name: ‘Jack’ };<br>// 存入对象<br>win.postMessage(JSON.stringify({key: ‘storage’, method: ‘set’, data: obj}), ‘<a target="_blank" rel="noopener" href="http://b.com&/#39;">http://b.com&#39;</a>);<br>// 读取对象<br>win.postMessage(JSON.stringify({key: ‘storage’, method: “get”}), “*”);<br>window.onmessage = function(e) {<br>  if (e.origin != ‘<a target="_blank" rel="noopener" href="http://a.com&/#39;">http://a.com&#39;</a>) return;<br>  // “Jack”<br>  console.log(JSON.parse(e.data).name);<br>};<br>子窗口接收消息的代码：</p>
<p>window.onmessage = function(e) {<br>  if (e.origin !== ‘<a target="_blank" rel="noopener" href="http://bbb.com&/#39;">http://bbb.com&#39;</a>) return;<br>  var payload = JSON.parse(e.data);<br>  switch (payload.method) {<br>    case ‘set’:<br>      localStorage.setItem(payload.key, JSON.stringify(payload.data));<br>      break;<br>    case ‘get’:<br>      var parent = window.parent;<br>      var data = localStorage.getItem(payload.key);<br>      parent.postMessage(data, ‘<a target="_blank" rel="noopener" href="http://aaa.com&/#39;">http://aaa.com&#39;</a>);<br>      break;<br>    case ‘remove’:<br>      localStorage.removeItem(payload.key);<br>      break;<br>  }<br>};</p>
<h4 id="6-通过WebSocket进行跨域"><a href="#6-通过WebSocket进行跨域" class="headerlink" title="6.通过WebSocket进行跨域"></a>6.通过WebSocket进行跨域</h4><p>web sockets是一种浏览器的API，它的目标是在一个单独的持久连接上提供全双工、双向通信。(同源策略对web sockets不适用)</p>
<p>web sockets原理：在js创建了web socket之后，会有一个HTTP请求发送到浏览器以发起连接。取得服务器响应后，建立的连接会使用HTTP升级从HTTP协议交换为web sockt协议。</p>
<p>只有在支持web socket协议的服务器上才能正常工作。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> socket = <span class="keyword">new</span> WebSockt(<span class="string">&#x27;ws://www.baidu.com&#x27;</span>);<span class="comment">//http-&gt;ws; https-&gt;wss</span></span><br><span class="line">socket.send(<span class="string">&#x27;hello WebSockt&#x27;</span>);</span><br><span class="line">socket.onmessage = <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> data = event.data;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h4 id="7-图像ping（单向）"><a href="#7-图像ping（单向）" class="headerlink" title="7.图像ping（单向）"></a>7.图像ping（单向）</h4><h5 id="什么是图像ping："><a href="#什么是图像ping：" class="headerlink" title="什么是图像ping："></a>什么是图像ping：</h5><p>图像ping是与服务器进行简单、单向的跨域通信的一种方式，请求的数据是通过查询字符串的形式发送的，而相应可以是任意内容，但通常是像素图或204相应（No Content）。 图像ping有两个主要缺点：首先就是只能发送get请求，其次就是无法访问服务器的响应文本。</p>
<h5 id="使用方法："><a href="#使用方法：" class="headerlink" title="使用方法："></a>使用方法：</h5><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> img = <span class="keyword">new</span> Image();</span><br><span class="line">img.onload = img.onerror = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">alert(<span class="string">&quot;done!&quot;</span>);</span><br><span class="line">&#125;;</span><br><span class="line">img.src = <span class="string">&quot;https://raw.githubusercontent.com/zhangmengxue/Todo-List/master/me.jpg&quot;</span>;</span><br><span class="line"><span class="built_in">document</span>.body.insertBefore(img,<span class="built_in">document</span>.body.firstChild);</span><br></pre></td></tr></table></figure>





<p>然后页面上就可以显示我放在我的github上某个地方的照片啦。</p>
<p>与<img>类似的可以跨域内嵌资源的还有:</p>
<p>(1)<script src></script>标签嵌入跨域脚本。语法错误信息只能在同源脚本中捕捉到。上面jsonp也用到了呢。</p>
<p>(2) <link src>标签嵌入CSS。由于CSS的松散的语法规则，CSS的跨域需要一个设置正确的Content-Type消息头。不同浏览器有不同的限制： IE, Firefox, Chrome, Safari (跳至CVE-2010-0051)部分 和 Opera。</p>
<p>(3)<video> 和 <audio>嵌入多媒体资源。</audio></video></p>
<p>(4)<object>, <embed> 和 <applet>的插件。</applet></object></p>
<p>(5)@font-face引入的字体。一些浏览器允许跨域字体（ cross-origin fonts），一些需要同源字体（same-origin fonts）。</p>
<p>(6) <frame> 和 <iframe>载入的任何资源。站点可以使用X-Frame-Options消息头来阻止这种形式的跨域交互。</iframe></p>
<h5 id="8-使用片段识别符来进行跨域"><a href="#8-使用片段识别符来进行跨域" class="headerlink" title="8.使用片段识别符来进行跨域"></a>8.使用片段识别符来进行跨域</h5><p>片段标识符（fragment identifier）指的是，URL的#号后面的部分，比如<a target="_blank" rel="noopener" href="http://example.com/x.html#flag%E7%9A%84#flag%E3%80%82%E5%A6%82%E6%9E%9C%E5%8F%AA%E6%98%AF%E6%94%B9%E5%8F%98%E7%89%87%E6%AE%B5%E6%A0%87%E8%AF%86%E7%AC%A6%EF%BC%8C%E9%A1%B5%E9%9D%A2%E4%B8%8D%E4%BC%9A%E9%87%8D%E6%96%B0%E5%88%B7%E6%96%B0%E3%80%82">http://example.com/x.html#flag的#flag。如果只是改变片段标识符，页面不会重新刷新。</a><br>父窗口可以把信息，写入子窗口的片段标识符。在父窗口写入：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">document</span>.getElementById(<span class="string">&#x27;frame&#x27;</span>).onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">var</span> src = <span class="string">&quot;http://127.0.0.1/JSONP/b.html&quot;</span> + <span class="string">&#x27;#&#x27;</span> + <span class="string">&quot;data&quot;</span>;</span><br><span class="line">    <span class="built_in">this</span>.src = src;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h6 id="子窗口通过监听hashchange事件得到通知。"><a href="#子窗口通过监听hashchange事件得到通知。" class="headerlink" title="子窗口通过监听hashchange事件得到通知。"></a>子窗口通过监听hashchange事件得到通知。</h6><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">&quot;b.html加载完成&quot;</span>)</span><br><span class="line">    <span class="built_in">window</span>.onhashchange = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">var</span> message = <span class="built_in">window</span>.location.hash;</span><br><span class="line">        <span class="built_in">console</span>.log(message)<span class="comment">//#data</span></span><br><span class="line">    &#125;;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h6 id="同样的，子窗口也可以改变父窗口的片段标识符。"><a href="#同样的，子窗口也可以改变父窗口的片段标识符。" class="headerlink" title="同样的，子窗口也可以改变父窗口的片段标识符。"></a>同样的，子窗口也可以改变父窗口的片段标识符。</h6><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">parent.location.href= target + <span class="string">&quot;#&quot;</span> + hash;</span><br></pre></td></tr></table></figure>

</body>
      
    </div>
    <div class="article-footer">
      <blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a href="https://xulujin.gitee.io/blog/2018/12/05/js%E4%B8%AD%E7%9A%84%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3/" title="js中的跨域及其解决的办法" target="_blank" rel="external">https://xulujin.gitee.io/blog/2018/12/05/js%E4%B8%AD%E7%9A%84%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3/</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用 <a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN协议</a> 许可协议。转载请注明出处！
    </li>
  </ul>
</blockquote>


<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://github.com/1314xulujin" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="/blog/images/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://github.com/1314xulujin" target="_blank"><span class="text-dark">LuKing-Xun</span><small class="ml-1x">前端工程师</small></a></h3>
        <div>邮箱:luking-xun@qq.com 微信:Element-UI</div>
      </div>
    </figure>
  </div>
</div>


    </div>
  </article>
  
    
  <section id="comments">
  	

    
  </section>


  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="/blog/2019/10/18/OOP%E6%80%9D%E6%83%B3-%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E6%80%9D%E6%83%B3/" title="OOP思想(面向对象思想)"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;Newer</span></a>
    </li>
    
    
    <li class="next">
      <a href="/blog/2018/10/22/javascript-jQuery/" title="javascript+jQuery"><span>Older&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
  </ul>
  
  
  <!-- Button trigger modal -->
  <button type="button" class="btn btn-fancy btn-donate pop-onhover bg-gradient-warning" data-toggle="modal" data-target="#donateModal"><span>$</span></button>
  <!-- <div class="wave-icon wave-icon-danger btn-donate" data-toggle="modal" data-target="#donateModal">
    <div class="wave-circle"><span class="icon"><i class="icon icon-bill"></i></span></div>
  </div> -->
  
  
  <div class="bar-right">
    
    <div class="share-component" data-sites="weibo,qq,wechat,facebook,twitter" data-mobile-sites="weibo,qq,qzone"></div>
    
  </div>
  </div>
</nav>
  
<!-- Modal -->
<div class="modal modal-center modal-small modal-xs-full fade" id="donateModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content donate">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <div class="modal-body">
        <div class="donate-box">
          <div class="donate-head">
            <p>Maybe you could buy me a cup of coffee.</p>
          </div>
          <div class="tab-content">
            <div role="tabpanel" class="tab-pane fade active in" id="alipay">
              <div class="donate-payimg">
                <img src="/blog/images/donate/alipay.jpg" alt="Scan Qrcode" title="Scan" />
              </div>
              <p class="text-muted mv">Scan this qrcode</p>
              <p class="text-grey">Open alipay app scan this qrcode, buy me a coffee!</p>
            </div>
            <div role="tabpanel" class="tab-pane fade" id="wechatpay">
              <div class="donate-payimg">
                <img src="/blog/images/donate/wechatpay.jpg" alt="Scan Qrcode" title="Scan" />
              </div>
              <p class="text-muted mv">Scan this qrcode</p>
              <p class="text-grey">Open wechat app scan this qrcode, buy me a coffee!</p>
            </div>
          </div>
          <div class="donate-footer">
            <ul class="nav nav-tabs nav-justified" role="tablist">
              <li role="presentation" class="active">
                <a href="#alipay" id="alipay-tab" role="tab" data-toggle="tab" aria-controls="alipay" aria-expanded="true"><i class="icon icon-alipay"></i> alipay</a>
              </li>
              <li role="presentation" class="">
                <a href="#wechatpay" role="tab" id="wechatpay-tab" data-toggle="tab" aria-controls="wechatpay" aria-expanded="false"><i class="icon icon-wepay"></i> wechat payment</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>



</main>

  <footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="https://github.com/1314xulujin" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="https://mail.qq.com/cgi-bin/loginpage" target="_blank" title="Email" data-toggle=tooltip data-placement=top><i class="icon icon-email"></i></a></li>
        
        <li><a href="/blog/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        <div class="publishby">
        	<!-- Theme by <a href="https://github.com/cofess" target="_blank"> cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>. -->
            更多功能正在开发中...
        </div>
    </div>
</footer>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>

<script src="/blog/js/plugin.min.js"></script>


<script src="/blog/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: 'Posts',
            PAGES: 'Pages',
            CATEGORIES: 'Categories',
            TAGS: 'Tags',
            UNTITLED: '(Untitled)',
        },
        ROOT_URL: '/blog/',
        CONTENT_URL: '/blog/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/blog/js/insight.js"></script>






   




   
    
<script src="//cdn.jsdelivr.net/npm/gitment@0.0.3/dist/gitment.browser.min.js"></script>
<script>
var gitment = new Gitment({
  // id默认为当前页面url，如果url后带参数或锚点，gitment要重新初始化
  // https://github.com/imsun/gitment/issues/55
  // 解决方案：id:window.location.pathname,或者将id设置为当前页面标题
  id: 'js中的跨域及其解决的办法', 
  owner: '1314xulujin', // 可以是你的GitHub用户名，也可以是github id
  repo: '1314xulujin.github.io',
  oauth: {
    client_id: 'f5572d863183b5e79cf9',
    client_secret: '8754b0d4afae1b366e75b4058a4b83a66ed82f05',
  }
})
gitment.render('comments')
</script>









</body>
</html>